package com.yy.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * @author young
 * @date 2022/12/24 20:47
 * @description:
 */
@Service
public class TestService {
    public String ok(Integer id) {
        return "时间为：" + DateUtil.format(LocalDateTime.now(), "yyyy年MM月dd日 HH:mm:ss") + "时，线程池:" + Thread.currentThread().getName() + "访问的id为：" + id;
    }


    /**
     * 出现系统超时或异常过后做服务降级，单侧服务端（提供方）降级
     *
     * @param id
     * @return
     */
    @HystrixCommand(
            fallbackMethod = "fallBackHandle", //指定一个服务异常后能够处理兜底的方法
            commandProperties = {
                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",
                            value = "5000")}) //设置超时处理，使该服务在5s内均可成功
    public String wait(Integer id) {
        //int a =10/0;
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "时间为：" + DateUtil.format(LocalDateTime.now(), "yyyy年MM月dd日 HH:mm:ss") + "时，等待后的线程池:" + Thread.currentThread().getName() + "访问的id为：" + id + "顺利执行";
    }

    public String fallBackHandle(Integer id) {
        return "接口异常后，走现在的回调方法" + Thread.currentThread().getName() + "系统繁忙";
    }

    /**
     * 用于测试服务熔断的模拟业务
     *
     * @param id
     * @return
     */
    @HystrixCommand(fallbackMethod = "circuitFallback", commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),//是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),//请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),//时间窗口期
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60"),//失败率达到多少后跳闸
    })
    public String getCircuitBreaker(Integer id) {
        if (id < 0) {
            throw new RuntimeException("id不能为负数");
        }
        String uuid = IdUtil.simpleUUID();

        return Thread.currentThread().getName() + "编号为：" + uuid;
    }

    /**
     * 回调方法
     *
     * @param id
     * @return
     */
    public String circuitFallback(Integer id) {
        return "id不能为负数，请稍后再试" + id;
    }
}
